package com.yzjs.wx.service;

import com.yzjs.base.BestPayServiceImpl;
import com.yzjs.base.PayRequest;
import com.yzjs.base.RefundRequest;
import com.yzjs.base.RefundResponse;
import com.yzjs.enumeration.BestPayTypeEnum;
import com.yzjs.enumeration.OrderStatusEnum;
import com.yzjs.wx.dao.MallRefundInfoMapper;
import com.yzjs.wx.dao.TAppUserInfoMapper;
import com.yzjs.wx.entity.MallRefundInfo;
import com.yzjs.wx.entity.TAppUserInfo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;

@Service
public class ReturnService {

    private static final Logger log = LoggerFactory.getLogger(ReturnService.class);

    @Autowired
    private BestPayServiceImpl bestPayService;


    @Autowired
    private MallRefundInfoMapper  refundInfoMapper ;

    @Autowired
    private TAppUserInfoMapper appUserInfoMapper ;




    /**
     * 发起支付退款信息
     */
    public RefundResponse create(String userId,String orderNo , BigDecimal orderAmout , BestPayTypeEnum bestPayTypeEnum){
        MallRefundInfo  refundInfo  = new MallRefundInfo();
        refundInfo.setUserId(userId);
        refundInfo.setOrderNo(Long.parseLong(orderNo));
        refundInfo.setOrderAmount(orderAmout);
        refundInfo.setPlatformStatus(OrderStatusEnum.SUCCESS.name());
        refundInfoMapper.insert(refundInfo);


        // 修改账户金额
        TAppUserInfo tAppUserInfo = appUserInfoMapper.selectByOpenId(userId);
        if (tAppUserInfo == null) {
            throw new RuntimeException("退款账户不存在，openId( = " + userId);
        }
        tAppUserInfo.setAccountAmount(tAppUserInfo.getAccountAmount().subtract(orderAmout));
        appUserInfoMapper.updateByPrimaryKeySelective(tAppUserInfo);

        RefundRequest payRequest = new RefundRequest();
        payRequest.setOrderId(orderNo);
        payRequest.setOrderAmount(orderAmout.doubleValue());
        payRequest.setPayTypeEnum(bestPayTypeEnum);
        RefundResponse refundResponse = bestPayService.refund(payRequest);
        log.info("[发起退款] response = {}",refundResponse);

        return refundResponse;
    }
}
